package rabbitmq

import (
	"github.com/astaxie/beego/logs"
	"github.com/spf13/viper"
	"github.com/streadway/amqp"
)

// 队列名常量
const (
	QueueSyncExternal = "niuren:queue:callback" // 同步外部联系人队列s
)

// Pool 用于存放rabbitmq channel pool的结构体
type Pool struct {
	NodeName string
	channel  *ChannelPool
}

var pool = make(map[string]*Pool, 0)

//Init 初始化
func Init() {
	nodes := viper.GetStringMap("rabbitmq")
	for nodeName := range nodes {
		p := &Pool{
			NodeName: nodeName,
			channel:  new(ChannelPool),
		}
		host := viper.GetString("rabbitmq." + nodeName + ".host")
		p.channel.InitPool(host, 10)
		logs.Info("[rabbitmq] 初始化 %s 连接池", nodeName)
		pool[nodeName] = p
	}
}

// Declare 声明一个队列
func (p *Pool) Declare(name string, durable bool, autoDelete bool, exclusive bool, noWait bool, args amqp.Table) {
	err := p.channel.QueueDeclarePassive(name, durable, autoDelete, exclusive, noWait, args)
	if err != nil {
		err = p.channel.QueueDeclare(name, durable, autoDelete, exclusive, noWait, args)
		if err != nil {
			logs.Critical("queue [" + name + "] queue init fail :(" + err.Error())
		}
	}
}

// Publish 发布消息
func (p *Pool) Publish(exchange, key string, mandatory, immediate, reliable bool, msg amqp.Publishing) (err error) {
	err = p.channel.Publish(exchange, key, mandatory, immediate, reliable, msg)
	return
}
